package com.lzl.service.impl;

import com.lzl.service.UploadService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service("toLocalUploadService")
public class ToLocalUploadServiceImpl implements UploadService {
    private static final Logger LOGGER = LoggerFactory.getLogger(ToLocalUploadServiceImpl.class);

    /*上传文件的保存目录*/
    public static final String UPLOAD_PATH = "/static/upload/";

    @Autowired
    private HttpServletRequest request;


    @Override
    public String uploadFile(MultipartFile uploadFile, String... allowFileExtends) throws Exception {
        Set<String> include = new HashSet<>(Arrays.asList(allowFileExtends));
        //获取保存路径
        String rootPath = request.getServletContext().getRealPath(UPLOAD_PATH);
        if(!uploadFile.isEmpty()){
            String fileName = uploadFile.getOriginalFilename();

            String extension = StringUtils.getFilenameExtension(fileName);

            if(!include.contains(extension)){
                throw new Exception("上传文件仅支持"+include+"扩展名！");
            }
            String uploadFileName = UUID.randomUUID()+"."+extension;
            File file = new File(rootPath,uploadFileName);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            try {
                uploadFile.transferTo(file);
                return UPLOAD_PATH+uploadFileName;
            }catch (Exception e){
                LOGGER.error("执行ToLocalUploadServiceImpl.uploadFile(MultipartFile,String[])查询错误.",e);
                throw e;
            }
        }
        return null;
    }
}
